//
//  PictureThinkViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2018/3/7.
//  Copyright © 2018年 史宵宵. All rights reserved.
//

#import "PictureThinkViewController.h"
#import "DreamPictureViewController.h"
#import "MyWorksListViewController.h"
#import "PhotoBrowseViewController.h"

@interface PictureThinkViewController ()<UITextViewDelegate>
@property (nonatomic,weak) JSTextView *moodTextView;
@property (nonatomic,weak) JSTextView *impressionTextView;
@end

@implementation PictureThinkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"涂鸦篇";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self creatDate];
    [self creatHeadView];
    [self creatFootView];
}
- (void)creatHeadView{
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor whiteColor];
    headView.frame = CGRectMake(0, 0, kScreenW, 200 + kScreenW/2+60);
    self.tableView.tableHeaderView = headView;
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.frame = CGRectMake((kScreenW - 60)/2, 10, 60, 60);
    titleLabel.font = [UIFont systemFontOfSize:25];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.clipsToBounds = YES;
    titleLabel.layer.cornerRadius = 30;
    [headView addSubview:titleLabel];
    
    UILabel *contentLabel = [[UILabel alloc]init];
    contentLabel.font = [UIFont systemFontOfSize:16];
    contentLabel.numberOfLines = 0;
    contentLabel.textColor = KTEXTMAINCOLOR;
    [headView addSubview:contentLabel];
    
    UIImageView *imageView = [[UIImageView alloc]init];
    [headView addSubview:imageView];

    
    
    UILabel *textLabel = [[UILabel alloc]init];
    textLabel.font = [UIFont systemFontOfSize:12];
    textLabel.textColor = KBACKNAVIGATIONCOLOR;
    textLabel.textAlignment = NSTextAlignmentCenter;
    
    
    if (self.image == nil) {
        titleLabel.text = @"思";
        titleLabel.backgroundColor = RGBColor(110, 188, 252);
        contentLabel.text = @"彩绘时，请先完成曼陀罗图形一侧的“绘前思考”，然后观看曼陀罗模板并把手放在模板上，体会画面的意义及所带来的感受。如看模板时，你觉得它像一朵盛开的莲花或翩翩起舞的蝴蝶，那么请体会莲花或蝴蝶带给你的心情";
        contentLabel.frame = CGRectMake(20, 80, kScreenW - 40, [Global getSizeOfString:contentLabel.text maxWidth:kScreenW - 40 maxHeight:MAXFLOAT withFontSize:16.6].height);
        textLabel.text = @"绘前思考";
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:KRECOMMENDLISTDEFAULT];
        imageView.userInteractionEnabled=YES;
        UITapGestureRecognizer *imagetap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImage:)];
        [imageView addGestureRecognizer:imagetap];
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"我的作品" target:self selector:@selector(myWorksList)];
    }else{
        titleLabel.text = @"写";
        titleLabel.backgroundColor = RGBColor(246, 204, 48);
        contentLabel.text = @"完成曼陀罗绘制后，可以尝试从不同角度来欣赏自己的作品，体会它所带来的心情及联想，并按照一侧“绘后思考”写出你想要表达的内容和记忆。";
        contentLabel.frame = CGRectMake(20, 80, kScreenW - 40, [Global getSizeOfString:contentLabel.text maxWidth:kScreenW - 40 maxHeight:MAXFLOAT withFontSize:16.6].height);
        textLabel.text = @"绘后思考";
        imageView.image = self.image;
    }
    imageView.frame = CGRectMake(kScreenW / 4, CGRectGetMaxY(contentLabel.frame) + 10, kScreenW/2, kScreenW/2);
    textLabel.frame = CGRectMake( (kScreenW - 60)/2, CGRectGetMaxY(imageView.frame) + 10, 60, 15);
    textLabel.backgroundColor = [UIColor whiteColor];
    
    UILabel *greenLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(imageView.frame) + 17, kScreenW - 20, 1)];
    greenLabel.backgroundColor = KBACKNAVIGATIONCOLOR;
    [headView addSubview:greenLabel];
    [headView addSubview:textLabel];
}
- (void)creatFootView{
    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor = [UIColor whiteColor];
    footView.frame = CGRectMake(0, 0, kScreenW, 100);
    self.tableView.tableFooterView = footView;
    
    CompleteButton *completeButton = [[CompleteButton alloc]initWithFrame:CGRectMake((kScreenW - 200)/2, 30, 200, 50) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:@"下一步"];
    completeButton.layer.cornerRadius = 25;
    [completeButton addTarget:self action:@selector(dreamPicture) forControlEvents:UIControlEventTouchUpInside];
    if (!strIsEmpty(self.answer1)) {
        [completeButton setTitle:@"完成保存" forState:UIControlStateNormal];
    }
    [footView addSubview:completeButton];
}
- (void)dreamPicture{
    if (strIsEmpty(self.moodTextView.text) || strIsEmpty(self.impressionTextView.text)) {
        [Global showActivityWithView:self.view withText:@"请补全信息"];
        return;
    }
    if (self.image == nil) {
        DreamPictureViewController *dreamPictureVC = [[DreamPictureViewController alloc]init];
        dreamPictureVC.pictureId = self.pictureId;
        dreamPictureVC.imageUrl = self.imageUrl;
        dreamPictureVC.answer1 = self.moodTextView.text;
        dreamPictureVC.answer2 = self.impressionTextView.text;
        [self.navigationController pushViewController:dreamPictureVC animated:YES];
    }else{
        NSString *urlStr = [JSPathUtil urlAppInterestAddManZuoPin];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
        if (!strIsEmpty(self.answer1)) {
            [dic setObject:self.answer1 forKey:@"answer1"];
            [dic setValue:self.answer2 forKey:@"answer2"];
        }
        [dic setObject:self.moodTextView.text forKey:@"answer3"];
        [dic setValue:self.impressionTextView.text forKey:@"answer4"];
        [dic setValue:self.pictureId forKey:@"dId"];
        
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", [Global timeStamp]];
            NSData *data = UIImageJPEGRepresentation(self.image, 1.0f);
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            
        } error:nil];
        
        AFURLSessionManager *manager=[[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        NSURLSessionUploadTask *uploadTask;
        uploadTask = [manager
                      uploadTaskWithStreamedRequest:request
                      progress:^(NSProgress * _Nonnull uploadProgress) {
                          
                      }
                      completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                          if (error) {
                              MyLog(@"Error: %@", error);
                          } else {
                              MyLog(@"%@ %@", response, responseObject);
                              NSError *err;
                              NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                                  options:NSJSONReadingMutableContainers
                                                                                    error:&err];
                              NSString *str = [NSString stringWithFormat:@"%@",dic[@"code"]];
                              if ([str isEqualToString:@"0"]) {
                                  [Global showActivityWithView:self.view withText:@"提交成功"];
                                  if (!strIsEmpty(self.answer1)) {
                                      NSInteger count = self.navigationController.viewControllers.count-5;
                                      [self.navigationController popToViewController:self.navigationController.viewControllers[count] animated:YES];
                                  }else{
                                      NSInteger count = self.navigationController.viewControllers.count-4;
                                      [self.navigationController popToViewController:self.navigationController.viewControllers[count] animated:YES];
                                  }
                                  
                              }
                              else
                                  [MBProgressHUD showMessage:dic[@"msg"]];
                          }
                      }];
        
        [uploadTask resume];
    }
}
//- (void)creatDate{
//    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
//    [dic setValue:self.pictureId forKey:@"id"]; //作品id
//    [yjNetWorkManger requestType:GET andURL:[JSPathUtil urlAppInterestGetManZuoPinById] andParmas:dic andComplition:^(id response, BOOL isuccess) {
//        if (isuccess) {
//            MyLog(@"%@",response);
//
//
//        }
//    }];
//}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    static NSString *CellIdentifier = @"cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (!cell) {
        UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        NSMutableArray *array = [[NSMutableArray alloc]initWithArray:@[@"1、你现在的心情如何？",@"2、今天什么事让你印象深刻？"]];
        if (!strIsEmpty(self.answer1)) {
            [array removeAllObjects];
            [array addObjectsFromArray:@[@"1、请给你的作品取一个名字？",@"2、你的作品让你联想到什么？"]];
        }
        UILabel *label = [[UILabel alloc]init];
        label.frame = CGRectMake(10, 5, kScreenW - 20, 20);
        label.font = [UIFont systemFontOfSize:14];
        label.text = array[indexPath.row];
        [cell.contentView addSubview:label];
    
        JSTextView *releaseContentTextView = [[JSTextView alloc] initWithFrame:CGRectMake(10, 30, kScreenW - 20, 80)];
        releaseContentTextView.font = [UIFont systemFontOfSize:16];
        releaseContentTextView.textColor = KTEXTMAINCOLOR;
        releaseContentTextView.delegate = self;
        releaseContentTextView.autocorrectionType = UITextAutocorrectionTypeNo;  //取消纠错
        releaseContentTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;  //取消首字母大写
        releaseContentTextView.returnKeyType = UIReturnKeyDefault;  //return改成done
        releaseContentTextView.clipsToBounds = YES;
        releaseContentTextView.layer.borderColor = KBORDERCOLOR.CGColor;
        releaseContentTextView.layer.borderWidth = 0.5;
        [cell.contentView addSubview:releaseContentTextView];
        if (indexPath.row) {
            self.impressionTextView = releaseContentTextView;
        }else{
            self.moodTextView = releaseContentTextView;
        }
        
        return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
#pragma mark - 点击放大
- (void)clickImage:(UITapGestureRecognizer *)sender{
    PhotoBrowseViewController *photo = [[PhotoBrowseViewController alloc] initWithimageArray:[[NSMutableArray alloc]initWithArray:@[self.imageUrl]] withIndex:0 withType:0];
    photo.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:photo];
    [self presentViewController:nc animated:YES completion:nil];
}
#pragma mark - 我的作品
- (void)myWorksList{
    MyWorksListViewController *myWorksListVC = [[MyWorksListViewController alloc]init];
    myWorksListVC.did = self.pictureId;
    [self.navigationController pushViewController:myWorksListVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
/*
 data =     {
 img = "/upload/jpeg/201803091433/1520577194510.jpeg",
 id = 6,
 answer4 = "<JSTextView: 0x1011e5000; baseClass = UITextView; frame = (10 30; 300 80); text = '天空'; clipsToBounds = YES; gestureRecognizers = <NSArray: 0x174447950>; layer = <CALayer: 0x174220820>; contentOffset: {0, 0}; contentSize: {300, 36}>",
 answer3 = "<JSTextView: 0x10110e000; baseClass = UITextView; frame = (10 30; 300 80); text = '星'; clipsToBounds = YES; gestureRecognizers = <NSArray: 0x17064c960>; layer = <CALayer: 0x1702381a0>; contentOffset: {0, 0}; contentSize: {300, 36}>",
 user_id = 111,
 answer2 = "碎碎的",
 answer1 = "第九十九",
 },
 */
@end
